package cn.wsw.hrm.service.impl;

import cn.wsw.hrm.client.RedisClient;
import cn.wsw.hrm.client.SmsClient;
import cn.wsw.hrm.domain.Sso;
import cn.wsw.hrm.mapper.SsoMapper;
import cn.wsw.hrm.service.ImageValidateCodeService;
import cn.wsw.hrm.util.AjaxResult;
import cn.wsw.hrm.util.StrUtils;
import cn.wsw.hrm.utils.VerifyCodeUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.aspectj.weaver.loadtime.Aj;
import org.bouncycastle.cms.PasswordRecipientId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;
import sun.plugin2.util.SystemUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ImageValidateCodeServiceImpl implements ImageValidateCodeService {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private SsoMapper ssoMapper;
    @Autowired
    private SmsClient smsClient;

    /**
     * 图形验证码
     * @param imageCodeKey
     * @return
     */
    @Override
    public String getCode(String imageCodeKey) {
        try {
            //随机生成6位验证码
            String code = VerifyCodeUtils.generateVerifyCode
                    (4).toLowerCase();
            System.out.println("111111111111111111111111");

            //写入redis               key       验证码   过期时间
            redisClient.addForTime(imageCodeKey, code, 60);
            System.out.println("22222222222222222222");

            //输出到图片
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            VerifyCodeUtils.outputImage(100, 30, data, code);
            //把图片加密返回
            BASE64Encoder encoder = new BASE64Encoder();
            System.out.println("============================");
            System.out.println(data.toByteArray());
            return encoder.encode(data.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return "操作错误";
        }
}


    /**
     * 短信验证码
     * @param param
     * @return
     */
    @Override
    public AjaxResult sendSmsCode(Map<String, String> param) {
        //获取手机号，手机验证码，手机验证码的key
        String mobile = param.get("mobile");
        String imageCode = param.get("imageCode");
        String imageCodeKey = param.get("imageCodeKey");
        //校验手机号是否为空
        if(mobile==null||"".equals(mobile)){
            return AjaxResult.me().setSuccess(false).setMessage("请输入手机号");
        }
//        检验图形验证码
        String key = redisClient.get("imageCodeKey");
        if (StringUtils.hasLength(key)||key.equals("imageCode")){
            return AjaxResult.me().setSuccess(false).setMessage("图形验证码错误");
        }
        //校验电话号码是否注册
        List<Sso> phone = ssoMapper.selectList(new EntityWrapper<Sso>().eq("phone", mobile));
        if (phone!=null||phone.size()>0){
            return AjaxResult.me().setSuccess(false).setMessage("该号码已注册");
        }
        //发送短信验证
        return sendSms(mobile);
    }
    public AjaxResult sendSms(String mobile){
        String smsKey = "SMS_CODE:"+mobile;
        //产生一个短信验证码
        String randomString = StrUtils.getComplexRandomString(4);
        //如果原来的短信验证码未过期，则再发一次
        //存入的是  验证码：时间
        String smsValue = redisClient.get("smsKey");  //code:time
        if (StringUtils.hasLength(smsValue)){
            String[] split = smsValue.split(":");
            //获取的上一次发送时间
            String timeStr = split[1];
            //验证发送时间是否已过
            long time = System.currentTimeMillis() - Long.valueOf(timeStr);
            //如果没有过期
            if (time<1000*60){
                return AjaxResult.me().setSuccess(false).setMessage("发送无效");
            }
            //如果过了，替换验证码
            randomString = split[0];
        }
        //存储到redis中
        redisClient.addForTime(smsKey,randomString+":"+System.currentTimeMillis(),60*5);
        //
        Map<String,String> params = new HashMap<>();
        //
        params.put("smsMobile",mobile);
        params.put("smsText","验证码为："+randomString+",5分钟后将失效");

        smsClient.send(params);
        return AjaxResult.me();
    }
}
